package com.xhx.accounting;

import androidx.appcompat.app.AppCompatActivity;

import android.app.AlertDialog;
import android.app.DatePickerDialog;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.os.Bundle;
import android.text.InputType;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ListView;
import android.widget.TextView;
import android.widget.Toast;

import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Objects;

public class plan_detail extends AppCompatActivity {
    private DBDao db;
    private Calendar calendar;
    private int listId;
    private TextView planName;
    private TextView goal, real;
    private TextView startTime, deadline;
    private Map<String, Object> record;
    private int planId;
    private long timeStamp;
    private Button listDatePicker;
    private ListViewAdapter2 mAdapter;
    private ListView lv;
    private List<Map<String, Object>> mData;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_plan_detail);
        Intent intent = getIntent();
        planId = intent.getIntExtra("planId", -1);

        db = new DBDao(this);
        mData = new ArrayList<>();
        record = db.getPlanDetail(planId);

        mData.addAll((List) record.get("list"));
        lv = findViewById(R.id.saving_lv);

        mAdapter = new ListViewAdapter2(this, mData);
        lv.setAdapter(mAdapter);

        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
        Date startTimeDate = new Date((Long) record.get("start_time") * 1000);
        Date deadlineDate = new Date((Long) record.get("deadline") * 1000);

        planName = findViewById(R.id.plan_title);
        goal = findViewById(R.id.goal);
        real = findViewById(R.id.real);
        startTime = findViewById(R.id.start_date);
        deadline = findViewById(R.id.finish_date);
        planName.setText(String.valueOf(record.get("saveplan_name")));

        startTime.setText(sdf.format(startTimeDate));
        deadline.setText(sdf.format(deadlineDate));

        goal.setText(String.valueOf(record.get("goal")));
        real.setText(String.valueOf(record.get("real")));

        calendar = Calendar.getInstance();
        listDatePicker = findViewById(R.id.add_button);

        if ((int) record.get("real") >= (int) record.get("goal")) {
            listDatePicker.setEnabled(false);
        } else {
            listDatePicker.setEnabled(true);
        }

        listDatePicker.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                showDatePickerDialog(plan_detail.this, 0);
            }
        });

        lv.setOnItemLongClickListener((parent, view, position, id) -> {
            HashMap<String, Object> listinfo = (HashMap<String, Object>) lv.getItemAtPosition(position);//SimpleAdapter返回Map
            Log.d("onLongClick", listinfo.toString());
            int id2 = (int) listinfo.get("id");
            AlertDialog.Builder builder = new AlertDialog.Builder(plan_detail.this);
            builder.setMessage("此操作不可撤销")
                    .setTitle("确定删除吗？");
            builder.setPositiveButton("确认", (dialog, id1) -> {
                // User clicked OK button
                db.deletePlanDetail(id2);
                refresh();
            });
            builder.setNegativeButton("取消", (dialog, id12) -> {
                // User cancelled the dialog
            });
            builder.show();
            return true;
        });
    }

    public void showDatePickerDialog(Context context, int themeResId) {
        new DatePickerDialog(context, themeResId, (view, year, month, dayOfMonth) -> {
            SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
            calendar.set(year, month, dayOfMonth);
            String listDate = sdf.format(calendar.getTime());
            try {
                timeStamp = Objects.requireNonNull(sdf.parse(listDate)).getTime() / 1000;
            } catch (ParseException e) {
                e.printStackTrace();
            }
            Log.d("DateStamp", String.valueOf(timeStamp));

            final EditText editText = new EditText(plan_detail.this);
            editText.setInputType(InputType.TYPE_CLASS_NUMBER);
            AlertDialog.Builder inputDialog =
                    new AlertDialog.Builder(plan_detail.this);
            inputDialog.setTitle("请输入金额").setView(editText);
            inputDialog.setNegativeButton("取消", new DialogInterface.OnClickListener() {
                @Override
                public void onClick(DialogInterface dialog, int which) {

                }
            });
            inputDialog.setPositiveButton("确定",
                    new DialogInterface.OnClickListener() {
                        @Override
                        public void onClick(DialogInterface dialog, int which) {
                            Log.d("DateStamp", String.valueOf(timeStamp));
                            int money = Integer.parseInt(editText.getText().toString());
                            db.addSavingRecord(timeStamp, planId, money);
                            refresh();
                        }
                    }).show();

        }, calendar.get(Calendar.YEAR), calendar.get(Calendar.MONTH), calendar.get(Calendar.DAY_OF_MONTH)).show();
    }


    public void onClick(View view) {
        switch (view.getId()) {
            case R.id.arrow_left:
                finish();
                break;
        }
    }

    private void refresh() {
        record = db.getPlanDetail(planId);
        real.setText(String.valueOf(record.get("real")));
        if ((int) record.get("real") >= (int) record.get("goal")) {
            listDatePicker.setEnabled(false);
        } else {
            listDatePicker.setEnabled(true);
        }
        mData.clear();
        mData.addAll((List) record.get("list"));
        mAdapter.notifyDataSetChanged();
    }
}